<script>
import * as echarts from "echarts";
import { COLORLIST, LineWidth, FittLineWidth } from "@/utils/variate";
export default {
  name: "LinePointDiagram",
  props: {
    // 图形数据
    value: {
      type: Object,
      default: () => {},
    },
    // 添加标识线
    markLine: {
      type: Array,
      default: () => [],
    },
    // 图形唯一ID，可不传
    id: {
      type: String,
      default: () => {
        var d = new Date().getTime();
        if (
          window.performance &&
          typeof window.performance.now === "function"
        ) {
          d += performance.now(); //use high-precision timer if available
        }
        var uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
          /[xy]/g,
          function(c) {
            var r = (d + Math.random() * 16) % 16 | 0; // d是随机种子
            d = Math.floor(d / 16);
            return (c == "x" ? r : (r & 0x3) | 0x8).toString(16);
          }
        );
        return uuid;
      },
    },
    // 标题
    title: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      myChart: null,
      graphType: true,
      contrast: ['拟合', '优化']
    };
  },
  watch: {
    value: {
      handler() {
        this.handleChange();
      },
      deep: true,
      // immediate: true,
    },
  },
  methods: {
    handleChange() {
      if (this.graphType) {
        this.initValue();
      } else {
        this.initPorintValue();
      }
    },

    // 初始化 线形图
    initValue() {
      this.$nextTick(() => {
        this.validateData()

        let option = {
          ...this.graphOptions(),
          series: Object.entries(this.value).map((item) => {
            return {
              name: item[0],
              type: "line",
              data: item[1],
              symbol: "none",
              itemStyle: {
                color: this.specialName(item[0]) && "#000",
              },
              lineStyle: {
                width: this.specialName(item[0]) ? FittLineWidth : LineWidth,
              },
              markLine: {
                symbol: "none",
                lineStyle: {
                  normal: {
                    color: "#000",
                  },
                },
                data: this.markLine.map((line) => ({
                  xAxis: item[1][line][0] || 0,
                })),
                label: {
                  fontSize: 20,
                },
              },
            };
          }),
        };

        window.removeEventListener("resize", this.resizeMyChart);
        window.addEventListener("resize", this.resizeMyChart);
        option && this.myChart && this.myChart.setOption(option, true);

        setTimeout(() => {
          const imgUrl = this.myChart && this.myChart.getConnectedDataURL({
            pixelRatio: 2, // 放大二倍下载
            backgroundColor: "#fff",
          });
          imgUrl && this.$emit("generateImg", imgUrl);
        }, 1000);
      });
    },

    // 判断图形的name中是否存在需要特殊处理的变量
    specialName(name) {
      if(!name) return ''

      // 如果传来的数据，都是拟合、优化数据，就不需要特殊处理
      const keys = Object.keys(this.value)
      const result = keys.every(hole => {
        return this.contrast.some(txt => hole.indexOf(txt) > -1)
      })
      if(result) {
        return false
      }

      // 区分展示
      return this.contrast.some(item => name.indexOf(item) > -1)
    },

    handleKeyCodeEvent() {
      // 监听键盘事件
      this.$nextTick(() => {
        document.addEventListener('keydown', (event) => {
          if(!this.myChart) return
          const xAxis = this.myChart.getModel().getComponent('dataZoom', 0)?.option
          const yAxis = this.myChart.getModel().getComponent('dataZoom', 1)?.option
          // console.log(xAxis, 'myChart');
    
          if (!xAxis || !yAxis) return
    
          if (event.key === 'x' || event.key === 'X') {
            xAxis.disabled = false
            yAxis.disabled = true
          } else if (event.key === 'y' || event.key === 'Y') {
            xAxis.disabled = true
            yAxis.disabled = false
          }
        });
      })
    },

    // 初始化 散点图
    initPorintValue() {
      this.$nextTick(() => {
        this.validateData()
        let option = {
          ...this.graphOptions(),
          series: Object.entries(this.value).map((item) => {
            return {
              symbolSize: 4,
              name: item[0],
              type: "scatter",
              data: item[1],
              // symbol: 'none',
              itemStyle: {
                color: this.specialName(item[0]) && "#000",
                width: 5,
              },
              markLine: {
                symbol: "none",
                lineStyle: {
                  normal: {
                    color: "#000",
                  },
                },
                data: this.markLine.map((line) => ({
                  xAxis: item[1][line][0] || 0,
                })),
                label: {
                  fontSize: 20,
                },
              },
            };
          }),
        };

        window.removeEventListener("resize", this.resizeMyChart);
        window.addEventListener("resize", this.resizeMyChart);
        option && this.myChart.setOption(option, true);

        setTimeout(() => {
          const imgUrl = this.myChart.getConnectedDataURL({
            pixelRatio: 2, // 放大二倍下载
            backgroundColor: "#fff",
          });
          this.$emit("generateImg", imgUrl);
        }, 1000);
      });
    },


    // 图形配置
    graphOptions() {
      return {
        color: COLORLIST,
        title: {
          text: this.title,
          // left:'center',
        },
        tooltip: {
          trigger: "axis",
          confine: true, // 限制tootip在容器内
          appendToBody: true,
          axisPointer: {
            type: "cross",
          },
        },
        toolbox: {
          feature: {
            saveAsImage: {},
          },
        },
        dataZoom: [
          {
            type: 'inside',
            orient: 'horizontal',
          },
          {
            type: 'inside',
            orient: 'vertical',
          }
        ],
        graphic: [
          {
            type: 'image',
            z: 100,
            top: 'auto',
            bottom: 'auto',
            right: 'center',
            zlevel: 100,
            id: 'logo',
            style: { 
              image: require('../../assets/imgs/watermark-logo.png'),
              height: 400,
              width: 900,
              y: 50,
            }
          }
        ],
        grid: {
          left: "5%",
          right: "10%",
          bottom: "5%",
          containLabel: true,
          borderWidth: 1,
          show: true,
          borderColor: "#000",
          zlevel: 99,
        },
        legend: {
          type: "scroll",
          orient: "vertical",
          align: "left",
          right: "0",
          top: "60",
          itemGap: 14,
          icon: "circle",
          itemWidth: 20, //圆点大小
          itemHeight: 10, // 粗细
          width: "100%",
          textStyle: {
            fontSize: 16,
          },
        },
        xAxis: {
          id: "x0",
          type: "value",
          name: "Time(s)",
          nameLocation: "middle",
          nameTextStyle: {
            fontSize: 22,
            padding: 20,
            color: "#000",
          },
          minorTick: {
            show: true,
          },
          axisLine: {
            onZero: false,
          },
          axisTick: {
            show: true,
            inside: true,
          },
          axisLabel: {
            fontWeight: 700,
            color: "#4c4c4c",
            fontSize: 20,
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: "#999",
              type: "dashed",
            },
          },
          // minorSplitLine: {
          //   show: true,
          //   lineStyle: {
          //     color: "#999",
          //     type: "dashed",
          //   },
          // },
        },
        yAxis: {
          id: "y0",
          type: "value",
          splitNumber: 4,
          name: "Response unit(RU)",
          nameLocation: "middle",
          nameTextStyle: {
            fontSize: 22,
            padding: 10,
            color: "#000",
          },
          nameGap: 50,
          minorTick: {
            show: true,
          },
          axisTick: {
            show: true,
            inside: true,
          },
          axisLine: {
            onZero: false,
            show: true,
            lineStyle: {
              color: "black",
            },
          },
          axisLabel: {
            formatter: "{value}",
            fontWeight: 700,
            color: "#4c4c4c",
            fontSize: 20,
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: "#999",
              type: "dashed",
            },
          },
        }
      };
    },

    // 校验元素数据，是否正确
    validateData() {
      if (Object.keys(this.value).length <= 0) return;
      const chartDom = document.getElementById(this.id);
      this.myChart = echarts.init(chartDom);
      this.handleKeyCodeEvent()

    },

    // 重置图形大小
    resizeMyChart() {
      this.myChart && this.myChart.resize();
    },
  },
  // 退出之前销毁
  beforeDestroy() {
    this.myChart && this.myChart.dispose();
  },
};
</script>
<template>
  <div class="linePointDiagram">
    <div class="switch_action">
      <el-switch
        v-model="graphType"
        active-color="#304156"
        inactive-color="#84adea"
        @change="handleChange"
        active-text="线形图"
        inactive-text="散点图"
      >
      </el-switch>
    </div>
    <div :id="id" class="graph" style="width: 80vw; height: 500px;"></div>
  </div>
</template>
<style lang="scss" scoped>
.linePointDiagram {
  width: 100%;
  height: 100%;
  .switch_action {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    padding-right: 240px;
  }
  // .graph {
  //   width: 100%;
  //   background: url('https://ddd.liangzhunglobal.com/liangzhun/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20240521154545.png') no-repeat;
  //   background-size: contain;
  //   background-position: center center;
  // }
}
</style>
